import React, { useEffect, useState } from 'react';
import { Tabs, Card } from 'antd';
import './index.css';
import TopicList from '../../components/TopicList';
import Pagination from '../../components/Pagination';
import Login from '../../components/Login';

const { TabPane } = Tabs;

const Home = () => {
  const [topicList, setTopicList] = useState<ITopic[]>([]);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [activeTab, setActiveTab] = useState('all');

  // 切换tab时将页码置1
  useEffect(() => {
    setCurrentPage(() => 1);
  }, [activeTab]);

  useEffect(() => {
    getList(activeTab, currentPage);
  }, [activeTab, currentPage]);

  // 获取数据
  const getList = async (tabType: string, page: number = 1) => {
    setTopicList([]);
    const response = await fetch(
      `https://cnodejs.org/api/v1/topics?tab=${tabType}&page=${page}`
    );
    const result = await response.json();
    setTopicList(result.data);
  };

  return (
    <div className="home">
      <main className="main">
        <Tabs defaultActiveKey="all" onChange={setActiveTab}>
          <TabPane tab="全部" key="all">
            <TopicList list={topicList} />
          </TabPane>
          <TabPane tab="精华" key="good">
            <TopicList list={topicList} />
          </TabPane>
          <TabPane tab="分享" key="share">
            <TopicList list={topicList} />
          </TabPane>
          <TabPane tab="问答" key="ask">
            <TopicList list={topicList} />
          </TabPane>
          <TabPane tab="招聘" key="job">
            <TopicList list={topicList} />
          </TabPane>
        </Tabs>
        <Pagination
          className="pages"
          showItemCount={5}
          startNum={1}
          currentPage={currentPage}
          onChange={(page: number) => setCurrentPage(page)}
        />
      </main>
      <aside className="aside">
        <Card title="个人信息">
          <Login />
        </Card>
        <Card
          className="about"
          title="关于本项目"
          style={{ marginTop: '1rem' }}
        >
          <p>
            项目地址{' '}
            <a href="https://github.com/Tuzilow/cnode-react-ts">
              https://github.com/Tuzilow/cnode-react-ts
            </a>
          </p>
          <p>
            作者 <a href="https://github.com/Tuzilow">Tuzilow</a>
          </p>
          <p>
            本项目使用React、Typescript、React
            Hooks、Ant-design等技术搭建，后台API来自
            <a href="https://cnodejs.org/api">CNode社区</a>
          </p>
        </Card>
      </aside>
    </div>
  );
};

export default Home;
